<template>
  <div>
    <van-field
      autocomplete="off"
      name="computed_region_four_name"
      :label="frontLabel + '地址所在地区'"
      placeholder="请选择地址所在的省、市、地区"
      @click="toShowFourAddress"
      readonly
      v-model="computed_region_four_name"
      :disabled="disabled"
    ></van-field>
    <nut-address
      v-model="showNutAddressInPopup"
      :province="province"
      :city="city"
      :country="country"
      :town="town"
      customAddressTitle="请选择"
      @onChange="onChangeArea"
      @close="closeArea"
    ></nut-address>

    <van-field
      autocomplete="off"
      v-model="computed_detail_address"
      name="computed_detail_address"
      :label="frontLabel + '详细地址'"
      placeholder="如: 道路（村庄）、门牌号、小区、楼栋号、单元室等信息"
      @input="handleInput"
      :rules="[
        {
          validator: value => {
            return wordCountLimit(value, 500)
          },
          message: '长度不能超过500位'
        }
      ]"
      rows="1"
      autosize
      type="textarea"
      :disabled="disabled"
    />
  </div>
</template>

<script>
import {videoObj} from '@/utils/videoLinkObj.js'
import {debounce} from 'lodash-es'
import {Toast} from 'vant'
import Jsonp from 'jsonp'
import provinceList from '../../constants/provinceList'
import {gaode_map_web_service_api} from '../../config/mapConfig'

export default {
  name: 'comFullAddressTwo',
  props: {
    frontLabel: String,
    keyWord: String,
    showFullAddressObj: Object,
    disabled: Boolean,
    isUpdate: Boolean
    // delay_time: Number,
  },
  data() {
    return {
      // 省
      province: provinceList,
      province_name: '',
      // 市
      city: [],
      city_name: '',
      // 县
      country: [],
      area_name: '',
      // 镇或者街道, 必传值：name
      town: [],
      street_name: '',

      showNutAddressInPopup: false,
      // wait_times: this.delay_time

      region_four_name_idList: [],
      region_four_name: ''
    }
  },

  computed: {
    // 由于对象数据均为异步获取，则无法及时渲染到页面。
    computed_region_four_name: {
      get() {
        return this.showFullAddressObj.region_four_name
      },
      set(value) {
        console.log('新的四级数据', value);
        // this.$emit('updateDetailAddress', value, this.keyWord)
      }
    },
    computed_detail_address: {
      get() {
        return this.showFullAddressObj.detail_address
      },
      set(value) {
        console.log('详细地址', value);
        this.$emit('updateDetailAddress', value, this.keyWord)
      }
    }
  },

  created() {
    console.warn('comFullAddressTwo---组件', JSON.stringify(this.showFullAddressObj));
  },

  methods: {
    rightClick(e) {
      window.location.href = videoObj[e.path[4].childNodes[0].innerText]
    },
    // 校验输入内容的字长
    wordCountLimit(val, wordCount) {
      return val.length <= wordCount
    },

    toShowFourAddress() {
      this.showNutAddressInPopup = !this.disabled
    },

    async _getAllAddress(id, nextKey, name) {
      const res = await this.$api.others.reqAllAddress(id)
      if (res.code === 200) {
        this[nextKey] = res.data
        // 分类讨论
        switch (nextKey) {
          case 'country':
            this.city_name = name
            break
          case 'town':
            this.area_name = name
            break
          default:
            this.province_name = name
        }
      }
    },

    onChangeArea(currentObj) {
      // 避免上次结果影响本次
      this[currentObj.next] = []
      switch (currentObj.next) {
        case 'country':
          // 得到县
          this._getAllAddress(currentObj.value.id, currentObj.next, currentObj.value.name)
          break
        case 'town':
          // 得到街道
          this._getAllAddress(currentObj.value.id, currentObj.next, currentObj.value.name)
          break
        default:
          // 得到市
          this._getAllAddress(currentObj.value.id, currentObj.next, currentObj.value.name)
      }
    },

    closeArea(obj) {
      console.log('关闭', obj);
      // 将下方的detail_address置为空，
      // 避免下面不改，而仅仅修改上面无法获取经纬度。
      this.detail_address = ''

      this.region_four_name = obj.data.addressStr
      let street_name_split = obj.data.addressStr.split(this.area_name);
      this.street_name = street_name_split.length > 0 ? street_name_split[street_name_split.length - 1] : ''

      // 得到的id形如这种形式： 1_8_9_0， 分割后得到一个数组
      this.region_four_name_idList = obj.data.addressIdStr.split('_');

      const regions = {
        provinceid: this.region_four_name_idList[0],
        provincename: this.province_name,
        cityid: this.region_four_name_idList[1],
        cityname: this.city_name,
        areaid: this.region_four_name_idList[2],
        areaname: this.area_name,
        streetid: this.region_four_name_idList[3],
        streetname: this.street_name,
        villageid: '',
        villagename: '',
        address: this.computed_detail_address,
        FulleAddress: this.region_four_name + this.computed_detail_address,
        long: '',
        lat: ''
      }

      // 生成数组
      const newObj = {
        region_four_name: this.region_four_name,
        detail_address: ''
      }
      this.$emit('updateRegionFourName', newObj, this.keyWord, regions)
    },

    // 获取经纬度-----封装函数
    // 改写为常规js的用法
    // todo   this的指向
    _getLongitudeLatitude: debounce(function (value) {
      // 高德地图
      this.$axios({
        url: 'https://restapi.amap.com/v3/geocode/geo',
        method: 'get',
        params: {
          key: gaode_map_web_service_api,
          address: value
        }
      }).then(res => {
        const {data} = res
        console.log('高德地图返回值', data)
        if (data.status === '1' && data.info === 'OK' && data.infocode === '10000') {
          this.location = data.geocodes[0].location.split(',')
          if (this.location.length === 2) {
            const regions = {
              provinceid: this.region_four_name_idList[0],
              provincename: this.province_name,
              cityid: this.region_four_name_idList[1],
              cityname: this.city_name,
              areaid: this.region_four_name_idList[2],
              areaname: this.area_name,
              streetid: this.region_four_name_idList[3],
              streetname: this.street_name,
              villageid: '',
              villagename: '',
              address: this.computed_detail_address,
              FulleAddress: this.region_four_name + this.computed_detail_address,
              long: this.location[0],
              lat: this.location[1]
            }

            console.log('当前的定位---高德地图', regions)
            this.$emit('getFullAddressValue', regions, this.keyWord)
          } else {
            Toast('请求高德地图的接口出错---获取经纬度异常！！请联系客服。')
          }
        }
      })

      // 百度地图
      /*const url = `http://api.map.baidu.com/geocoding/v3/?address=${value}&output=json&ak=${baidu_map_web_js_api}&callback=showLocation`;
      Jsonp(url, {}, (err, res) => {
        const data = res
        console.log('百度地图', data)
        if (data.status === 0){
          const location = data.result.location;
          const regions = {
            provinceid: (this.region_four_name_idList)[0],
            provincename: this.province_name,
            cityid: (this.region_four_name_idList)[1],
            cityname: this.city_name,
            areaid: (this.region_four_name_idList)[2],
            areaname: this.area_name,
            streetid: (this.region_four_name_idList)[3],
            streetname: this.street_name,
            villageid: '',
            villagename: '',
            address: this.computed_detail_address,
            FulleAddress:  this.region_four_name + this.computed_detail_address,
            long: location.lng,
            lat: location.lat,
          };
          console.log('当前的定位----百度地图', regions)
          this.$emit('getFullAddressValue', regions, this.keyWord);

        } else {
          Toast('请求百度地图接口出错---获取经纬度异常！！请联系客服。')
        }
      })*/
    }, 1800),

    handleInput(value) {
      // 防抖函数：触发事件后在n秒后执行，如果n秒内又触发事件，则重新计算时间。
      // 节抖的用法
      if (this.computed_region_four_name && this.computed_detail_address) {
        const fullAddress = this.computed_region_four_name + value
        this._getLongitudeLatitude(fullAddress)
      }
    }
  }
}
</script>

<style scoped></style>
